package com.kaiwukj.android.ufamily.utils.upload;

import androidx.annotation.IntDef;
import androidx.annotation.NonNull;

import com.kaiwukj.android.ufamily.mvp.http.api.Api;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

/**
 * 七牛云文件工具类
 *
 * @author huiwings
 * 2020-03-24
 */
public class UploadUtils {

    public static final int IMAGE = 0;
    public static final int AUDIO = 1;
    public static final int VIDEO = 2;

    @IntDef({IMAGE, AUDIO, VIDEO})
    @Target(ElementType.PARAMETER)
    @Retention(RetentionPolicy.SOURCE)
    public @interface MediaType {
    }

    private volatile static UploadUtils instance;
    private OnUploadListener mListener;

    private List<UploadBean> urls = new ArrayList<>();

    private int count = 0;

    private boolean isList() {
        return count > 0;
    }

    public UploadUtils() {
    }

    public UploadUtils(Builder builder) {
        mListener = builder.listener;
    }

    /*public void setOnUploadListener(OnUploadListener listener) {
        mListener = listener;
    }*/

    /**
     * 使用单例会导致listener冲突
     *
     * @return
     */
    @Deprecated
    public static UploadUtils getInstance() {
        if (instance == null) {
            synchronized (UploadUtils.class) {
                if (instance == null) {
                    instance = new UploadUtils();
                }
            }
        }
        return instance;
    }


    public void upload(String filePath, String token, @MediaType int mediaType, OnUploadListener listener) {
        String fileName = UUID.randomUUID().toString();
        switch (mediaType) {
            case IMAGE:
                fileName += ".jpg";
                break;
            case AUDIO:
                fileName += ".amr";
                break;
            case VIDEO:
                fileName += ".mp4";
                break;
            default:
                break;
        }
        upload(filePath, fileName, token, listener);
    }

    public void upload(String filePath, String fileName, String token, OnUploadListener listener) {
        mListener = listener;
        uploadFile(filePath, fileName, token);
    }

    public void uploadImages(List<String> paths, String token, OnUploadListener listener) {
        mListener = listener;
        count = paths.size();
        urls.clear();
        for (int i = 0; i < paths.size(); i++) {
            String fileName = String.format("%s_%s.jpg", UUID.randomUUID().toString(), i);
            uploadFile(paths.get(i), fileName, token);
        }

    }

    private Configuration getConfig() {
        return new Configuration.Builder()
                .connectTimeout(10)              // 链接超时。默认10秒
                //.useHttps(true)                // 是否使用https上传域名
                .responseTimeout(60)             // 服务器响应超时。默>/sdcard/img_1585116590274.jpg.jpg认60秒
                // .recorder(recorder)           // recorder分片上传时，已上传片记录器。默认null
                // .recorder(recorder, keyGen)   // keyGen 分片上传时，生成标识符，用于片记录器区分是那个文件的上传记录
                .zone(Api.zone)                  // 设置区域，不指定会自动选择。指定不同区域的上传域名、备用域名、备用IP。
                .build();
    }

    /**
     * 文件上传
     *
     * @param filePath 文件路径
     * @param fileName 文件名
     * @param token    七牛token
     */
    private synchronized void uploadFile(@NonNull final String filePath, @NonNull String fileName, @NonNull final String token) {
        //LogUtils.d("filePath-------------->" + filePath);
        UploadManager uploadManager = new UploadManager(getConfig(), 3);
        uploadManager.put(filePath, fileName, token, (key, info, response) -> {
            if (info.isOK()) {
                UploadBean bean = new UploadBean(key);
                if (isList()) {
                    urls.add(bean);
                    if (mListener != null) {
                        if (urls.size() == count) {
                            sortResult(urls);
                            mListener.onUploadImages(urls);
                            count = 0;
                        }
                    }
                } else {
                    if (mListener != null) {
                        mListener.onUploadImage(bean);
                    }
                }
            } else {
                if (mListener != null) {
                    mListener.onError(info.statusCode, info.error);
                }
                if (isList()) {
                    //部分情况下可能会存在问题
                    count = 0;
                }
            }
        }, new UploadOptions(null, null, false, (key, percent) -> {

        }, null));
    }


    /**
     * 对多个结果进行排序
     *
     * @param result
     */
    private void sortResult(List<UploadBean> result) {
        Collections.sort(result, (o1, o2) -> getIndexByFileName(o1.getUrl()) - getIndexByFileName(o2.getUrl()));
    }

    private int getIndexByFileName(String fileName) {
        int start = fileName.indexOf("_");
        int end = fileName.indexOf(".");
        try {
            return Integer.parseInt(fileName.substring(start + 1, end));
        } catch (NumberFormatException e) {
            return 0;
        }
    }


    public static class Builder {
        private OnUploadListener listener;

        public Builder listener(OnUploadListener listener) {
            this.listener = listener;
            return this;
        }

        public UploadUtils build() {
            return new UploadUtils(this);
        }

    }

}
